package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询用户最新订单和订单详情(连接查询)
     * @param curPage
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public Page<OrdersDto> queryUserOrderByPage(Integer curPage, Integer pageSize, Long userId) {
        Page<OrdersDto> page = new Page<>(curPage, pageSize);
        return ordersMapper.queryUserOrderByPage(page, userId);
    }

    /**
     * 查询用户最新订单和订单详情(嵌套查询)
     * @param curPage
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public Page<OrdersDto> queryUserOrderNestDetail(Integer curPage, Integer pageSize, Long userId) {
        Page<OrdersDto> page = new Page<>(curPage, pageSize);
        return ordersMapper.queryUserOrderNestDetail(page, userId);
    }

    /**
     * 用户提交订单
     * @param ordersDto
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitOrder(OrdersDto ordersDto) {
        // 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 查询当前用户信息
        User user = userService.getById(userId);
        // 查询下单地址信息
        AddressBook addressBook = addressBookService.getById(ordersDto.getAddressBookId());
        // 查询用户的购物车
        List<ShoppingCart> shoppingCarts = shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId, userId).list();
        // 生成订单id
        Long orderId = IdWorker.getId();
        // 计算订单总金额,设置订单详情
        List<OrderDetail> orderDetails = new ArrayList<>();
        BigDecimal orderAmount = new BigDecimal("0.00");
        for (ShoppingCart shoppingCart : shoppingCarts) {
            // 计算订单总金额
            BigDecimal shoppingAmount = shoppingCart.getAmount()
                    .multiply(new BigDecimal(shoppingCart.getNumber()));
            orderAmount = orderAmount.add(shoppingAmount);
            // 设置订单详情
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetails.add(orderDetail);
        }
        // 设置订单
        ordersDto.setId(orderId);
        ordersDto.setNumber(UUID.randomUUID().toString());
        ordersDto.setStatus(2);
        ordersDto.setUserId(userId);
        ordersDto.setOrderTime(LocalDateTime.now());
        ordersDto.setCheckoutTime(LocalDateTime.now());
        ordersDto.setAmount(orderAmount);
        ordersDto.setPhone(addressBook.getPhone());
        ordersDto.setAddress(addressBook.getDetail());
        ordersDto.setUserName(user.getName());
        ordersDto.setConsignee(addressBook.getConsignee());
        // 添加订单表
        ordersMapper.insert(ordersDto);
        // 添加订单详情表
        orderDetailService.saveBatch(orderDetails);
        // 清空用户的购物车
        shoppingCartService.lambdaUpdate().eq(ShoppingCart::getUserId, ordersDto.getUserId()).remove();
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitOrderAgain(Long id) {
        // 根据订单id查询订单和订单明细
        OrdersDto ordersDto = ordersMapper.queryOrdersDtoById(id);
        // 设置订单信息
        ordersDto.setId(null);
        ordersDto.setNumber(UUID.randomUUID().toString());
        ordersDto.setStatus(2);
        ordersDto.setOrderTime(LocalDateTime.now());
        ordersDto.setCheckoutTime(LocalDateTime.now());
        // 保存新订单
        ordersMapper.insert(ordersDto);
        // 设置订单明细
        List<OrderDetail> orderDetails = ordersDto.getOrderDetails();
        for (OrderDetail orderDetail : orderDetails) {
            orderDetail.setId(null);
            orderDetail.setOrderId(ordersDto.getId());
        }
        // 保存订单明细
        orderDetailService.saveBatch(orderDetails);
    }
}
